package mg.daloji.antandroyd.ui;

import java.util.ArrayList;
import java.util.HashMap;
import mg.daloji.antandroyd.R;
import mg.daloji.antandroyd.application.App;
import mg.daloji.antandroyd.service.IServiceRadio;
import mg.daloji.antandroyd.service.IServiceRadioCallBack;
import mg.daloji.antandroyd.service.ServiceRadio;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class Homes extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

	private static final int TEXT_UPDATE = 0;
	private static String PACKAGE ="com.speakingcode.example.android.MediaPlayerService";
	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mMediaPlayer;
	
	private ServiceRadio service;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;

	private Context mContext;

	private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
	
	
	private IServiceRadioCallBack mObserver;
	private ServiceConnection mConnection;
	
	
	
	private boolean mBound =false; 
	private boolean isplaying =false;
	private ProgressDialog mProgressDialog;
	private IServiceRadio mService;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		mContext=getApplicationContext();
		mProgressDialog = new ProgressDialog(this);
		songTitleLabel=(TextView) findViewById(R.id.songTitle);
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		
		/**
		 * Play button click event
		 * plays a song and changes button to pause image
		 * pauses a song and changes button to play image
		 * */
		btnPlay.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// check for already playing
				if(mBound){
					try{
						if(!isplaying){
							isplaying=false;
						    btnPlay.setImageResource(R.drawable.btn_pause);
						    //service.initializePlayer(App.getConf().get(0).getUrl());
					        //mService.doStart(mObserver, App.getConf().get(0).getUrl());
						}else{
							isplaying=true;
					    	 btnPlay.setImageResource(R.drawable.btn_play);
					    	 mService.doStop(mObserver);
						}
					}catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
				case TEXT_UPDATE:
					songTitleLabel.setText((CharSequence) msg.obj);
				}
			}
		};
		
		mObserver = new IServiceRadioCallBack.Stub() {
			public void streamingReady() throws RemoteException {
				Message msg = mHandler.obtainMessage(TEXT_UPDATE, "");
				mHandler.sendMessage(msg);
			}

			@Override
			public void errorStreaming() throws RemoteException {
				// TODO Auto-generated method stub
				
			}
		};
		mConnection = new ServiceConnection(){	
			public void onServiceDisconnected(ComponentName name) {
				mService = null;
				Toast.makeText(mContext, "ServiceConnection onServiceDisConnected calle by "
						+ Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
			}

			@Override
			public void onServiceConnected(ComponentName arg0, IBinder service) {
				// TODO Auto-generated method stub
				mService =  IServiceRadio.Stub.asInterface(service);
				Toast.makeText(mContext, "ServiceConnection onServiceConnected called by "
						+ Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
				try{
					mService.setObserver(mObserver);
				}catch(RemoteException e){
				}
				mBound = true;
			}
		};
		bindService();
	}



	/** Determines if the MediaPlayerService is already running.
	 * @return true if the service is running, false otherwise.
	 */
	private boolean MediaPlayerServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if (PACKAGE.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}




	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
	protected void onActivityResult(int requestCode,
			int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}


	
	private void bindService(){
		Intent intent = new Intent(getApplicationContext(), ServiceRadio.class);
		bindService(intent, mConnection, BIND_AUTO_CREATE);
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		mMediaPlayer.release();
	}

	@Override
	public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}


}